package com.example.myapplication.Teacher;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.example.myapplication.Data.Course;
import com.example.myapplication.Data.CourseDetailData;
import com.example.myapplication.Data.UserData;
import com.example.myapplication.R;
import com.example.myapplication.Student.SignInActivity;
import com.example.myapplication.Tool.TimestampTool;
import com.example.myapplication.http.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Tea_MyDetailActivity extends AppCompatActivity {

    private Course course;
    private UserData userData;
    private Button btTeaPostSign;

    private final Gson gson = new Gson();

    private int code;// 响应码
    private String msg;// 提示信息
    private Object data;// 实际数据
    private Button btTeaCourseDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tea_my_detail);
        initView();
        get();

        btTeaCourseDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(Tea_MyDetailActivity.this);
                // 设置对话框标题和消息
                builder.setTitle("警告！")
                        .setMessage("该课程将彻底删除！是否确认删除课程。");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();// 关闭对话框
                        getbtTeaCourseDelete();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                // 创建并显示 AlertDialog
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

        btTeaPostSign.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(Tea_MyDetailActivity.this,TeaPostSignActivity.class);
                // 将被点击项的数据传递给下一个活动
                intent.putExtra("course", course);
                intent.putExtra("userData", userData);
                startActivity(intent);
            }
        });
    }

    private void get(){
        new Thread(() -> {
            //构建请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            // 构建请求URL
            String url = "http://47.107.52.7:88/member/sign/course/detail"
                    + "?courseId=" + course.getCourseId()
                    + "&userId=" +userData.getId();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    .headers(headers)//将请求头加至请求中
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(DetailDisplay);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            };
        }).start();
    }
    /**
     * 回调
     */
    private final Callback DetailDisplay = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handleResponse(); // 调用处理响应的方法
                }
            });
        }
    };
    private void handleResponse() {
        if (code == 200) {
            // 请求成功
            if (data != null) {
                Log.d("cpy---请求成功", String.valueOf(code));
                //将获取的数据存入CourseDetailData工具类。
                JsonObject jsonObject = gson.toJsonTree(data).getAsJsonObject();
                CourseDetailData courseDetailData = gson.fromJson(jsonObject, CourseDetailData.class);

                ImageView iv_detail_course_photo = findViewById(R.id.iv_detail_course_photo);
                TextView tv_course_name = findViewById(R.id.tv_sign_in_course_name);
                TextView tv_detail_college_name = findViewById(R.id.tv_detail_college_name);
                TextView tv_detail_real_name = findViewById(R.id.tv_detail_real_name);
                TextView tv_detail_start_time = findViewById(R.id.tv_detail_start_time);
                TextView tv_detail_end_time = findViewById(R.id.tv_detail_end_time);
                TextView tv_detail_has_select = findViewById(R.id.tv_detail_has_select);
                TextView tv_detail_introduce = findViewById(R.id.tv_detail_introduce);
                TextView tv_course_title_name = findViewById(R.id.tv_course_title_name);

                String startTime = TimestampTool.timestampToDateTime(courseDetailData.getStartTime());
                String endTime = TimestampTool.timestampToDateTime(courseDetailData.getEndTime());

                Glide.with(this)
                        .load(courseDetailData.getCoursePhoto())//图片网址
                        .apply(new RequestOptions().centerCrop()) // 可选：设置图片缩放类型
                        .transition(DrawableTransitionOptions.withCrossFade()) // 可选：添加淡入淡出效果
                        .into(iv_detail_course_photo);
                tv_course_title_name.setText(courseDetailData.getCourseName());
                tv_course_name.setText(courseDetailData.getCourseName());
                tv_detail_college_name.setText(courseDetailData.getCollegeName());
                tv_detail_real_name.setText(courseDetailData.getRealName());
                tv_detail_start_time.setText(startTime);
                tv_detail_end_time.setText(endTime);
                if(courseDetailData.getHasSelect()){
                    tv_detail_has_select.setText("已结课");
                } else {
                    tv_detail_has_select.setText("未结课");
                }
                tv_detail_introduce.setText(courseDetailData.getIntroduce());

            }
        } else {
            // 请求失败
            if (msg != null) {
                Log.d("请求失败", msg);
            }
        }
    }
    private void getbtTeaCourseDelete(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/course/teacher" +
                    "?courseId=" + course.getCourseId() +
                    "&userId="+ userData.getId();

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .delete()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handleCourseDropResponse();
                }
            });
        }
    };
    private void handleCourseDropResponse(){
        if (code == 200) {
            // 请求成功
            Toast.makeText(Tea_MyDetailActivity.this, "删除成功", Toast.LENGTH_LONG).show();
        } else {
            // 请求失败
            if (msg != null) {
                Toast.makeText(Tea_MyDetailActivity.this, msg, Toast.LENGTH_LONG).show();
                Log.d("请求失败", msg);
            }
        }
    }

    private void initView() {
        btTeaCourseDelete=findViewById(R.id.bt_Tea_Course_Delete);
        btTeaPostSign=findViewById(R.id.bt_tea_post_sign);
        //获取数据
        course = (Course) getIntent().getSerializableExtra("courseData");
        userData = (UserData) getIntent().getSerializableExtra("userData");
        Log.d("cpy---course", String.valueOf(course));
    }
}